<template>
  <a-layout style="height: 100%">
    <a-spin :spinning="loading" tip="正在分析..." style="max-height: 100%;">
      <a-layout-content style="height: 100%;">
        <a-row style="height: 100%;">
          <!-- 左侧：代码输入 -->
          <a-col :span="9" style="display: flex; flex-direction: column; padding: 10px; border-right: 1px solid #ddd; height: 100%;">
            <a-card title="代码输入" style="flex: 1; display: flex; flex-direction: column;">


              <!-- 模式选择 -->
              <a-select v-model:value="selectedMode" style="width: 100px; margin-bottom: 10px;">
                <a-select-option value="AI">AI</a-select-option>
                <a-select-option value="Normal">Normal</a-select-option>
                <a-select-option value="Hybrid">Hybrid</a-select-option>

              </a-select>


              <!-- 语言选择 -->
              <a-select   v-if="selectedMode !== 'Normal'"  v-model:value="selectedLang" style="width: 120px; margin-bottom: 10px;margin-left: 10px">
                <a-select-option value="C">C 语言</a-select-option>
                <a-select-option value="Python">Python</a-select-option>
              </a-select>
              <!-- 模型选择 -->
              <a-select   v-if="selectedMode !== 'Normal'"  v-model:value="selectedModel" style="width: 150px; margin-bottom: 10px;margin-left: 10px">
                <a-select-option value="gpt-3.5-turbo">gpt-3.5-turbo</a-select-option>
                <a-select-option value="gpt-4o">gpt-4o</a-select-option>
                <a-select-option value="gpt-4">gpt-4</a-select-option>
                <a-select-option value="deepseek-r1-lyt">deepseek-r1</a-select-option>
              </a-select>



              <!-- 代码输入框 -->
              <!--            <a-textarea-->
              <!--                v-model:value="code"-->
              <!--                placeholder="请输入代码..."-->
              <!--                style="flex: 1 1 0%; height: 75vh;resize: none"-->
              <!--            />-->
              <div ref="editorContainer" style="flex: 1 1 0%; height: 78vh;"></div>
              <!-- 提交按钮 -->
              <a-button type="primary" block style="margin-top: 10px;" @click="submitCode">
                分析代码
              </a-button>
            </a-card>
          </a-col>

          <!-- 右侧：分析结果 -->
          <a-col :span="9" style="padding: 10px; height: 100%; overflow-y: auto;">
            <a-card title="控制流图 (CFG)" style=" height: 100%">
              <!--            <div id="cfg-container" style="height: 300px; overflow: auto;">{{ cfg }}</div>-->
              <CFGGraph :cfgData="cfg"  />
            </a-card>

          </a-col>

          <a-col :span="6" style="padding: 10px; height: 100%; overflow-y: auto;">
            <DUComponent :duRaw="du" />
<!--            <a-card title="定义-使用链 (DU)" style="margin-top: 20px;">-->
<!--              <div id="du-container" style="height: 300px; overflow: auto;">{{ du }}</div>-->
<!--            </a-card>-->
          </a-col>
        </a-row>
      </a-layout-content>
    </a-spin>
  </a-layout>
</template>

<script>
import CFGGraph from "@/components/CFGGraph";
import DUComponent from "@/components/DUComponent";
import * as monaco from 'monaco-editor';
import {message} from 'ant-design-vue';
export default {
  components: { CFGGraph ,DUComponent},
  data() {
    return {
      code: '',
      selectedLang: 'C',
      selectedModel: 'gpt-3.5-turbo',
      selectedMode: 'AI',
      cfg: null,
      du: null,
      loading: false
    };
  },
  mounted() {
    this.initializeEditor();
  },
  methods: {
    initializeEditor() {
      // 初始化 Monaco Editor
      this.editor = monaco.editor.create(this.$refs.editorContainer, {
        value: this.code,
        language: this.selectedLang.toLowerCase(),
        theme: 'vs-light',
        automaticLayout: true,
        // 配置缩进相关设置
        tabSize: 2,  // 设置每个 Tab 为 2 个空格
        insertSpaces: true,  // 使用空格代替 Tab
        detectIndentation: true,  // 自动检测缩进
      });

      // 当代码内容变化时更新 data
      this.editor.onDidChangeModelContent(() => {
        this.code = this.editor.getValue();
      });
    },
    async submitCode() {
      message.info("提交成功！")
      this.loading = true;
      try {
        const response = await fetch('http://101.42.54.47:5000/analyzecfg', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            code: this.code,
            language: this.selectedLang,
            model: this.selectedModel,
            mode: this.selectedMode
          })
        });



        const data = await response.json();
        let cleanedData = data.data
        console.log(data.data)
        if(this.selectedMode!="Normal")
        {
          // 去除 Markdown 代码块 (` ```json ... ``` `)
          cleanedData = data.data.replace(/^```json\n/, "").replace(/\n```$/, "");
        }


        // 解析 JSON
        this.cfg = JSON.parse(cleanedData);
      } catch (error) {
        message.warn('AI返回的格式错误，请稍等重新提交！')
        console.error('请求失败:', error);
      }
      try {
        const response = await fetch('http://101.42.54.47:5000/analyzedu', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            code: this.code,
            language: this.selectedLang,
            model: this.selectedModel,
            mode: this.selectedMode
          })
        });
        const data = await response.json();
        let newdata = data.data
        if(this.selectedMode!="Normal")
        {
          // 去除 Markdown 代码块 (` ```json ... ``` `)
          newdata = data.data.replace(/^```json\n/, "").replace(/\n```$/, "");
        }

        this.du  = newdata
        console.log(this.du)
      } catch (error) {
        console.error('请求失败:', error);
      }
      this.loading = false;
    }
  }
};
</script>

<style>
#cfg-container, #du-container {
  border: 1px solid #ccc;
  padding: 10px;
  min-height: 200px;
  overflow: auto;
}
html, body, #app {
  height: 100%;
  margin: 0;
}
</style>
